/*
 Copyright (c) Whitemice Consulting, 2007, 2008, 2009
 Adam Tauno Williams <awilliam@whitemice.org>
 License: MIT/X11

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
*/
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using Gtk;
using Whitemice.ZOGI;
using Whitemice.ZOGI.GtkWidgets;

namespace Whitemice.Consonance
{
  public abstract class EntityWindow : Gtk.Window, 
                                       IEntityWindow,
                                       IZOGIWidget
  {
    protected int                 freezeDepth;
    protected bool                isAlive;
    protected bool                closeOnThaw = false;
    protected MultiResultCallback callback;
  
    public EntityWindow() : this(Gtk.WindowType.Toplevel)
    {
    } // end ctor
    
    public EntityWindow(Gtk.WindowType type) : base(type)
    {
      callback = new MultiResultCallback(this.ReceiveDataCallback);
      isAlive = true;
    } // end ctor
  
    protected void Freeze()
    {
      this.ZLOG("Freeze");
      if (this.GdkWindow != null)
      {
        this.GdkWindow.Cursor = new Gdk.Cursor(Gdk.CursorType.Watch);
        this.Sensitive = false;
      }
    } // end Freeze
    
    protected void FreezeToDepth(int depth)
    {
      freezeDepth = depth;
      Freeze();
    } // end FreezeToDepth
    
    protected void Thaw()
    {
      this.ZLOG("Thaw");
      if (closeOnThaw)
      {
        this.ZLOG("Destroying EntityWindow");
        Registry.UnregisterForNotification(this);
        this.Destroy();
      } else
        {
          if (this.GdkWindow != null)
          {
            this.GdkWindow.Cursor = new Gdk.Cursor(Gdk.CursorType.TopLeftArrow);
            this.Sensitive = true;
          } else this.ZLOG("No GDK Window reference available.");
        }
    } // end Thaw
    
    protected void ThawOneLevel()
    {
      if (freezeDepth > 0)
        freezeDepth--;
      if (freezeDepth == 0)
        Thaw();
    } // end ThawOneLevel
    
    public void ThawOneLevel(object sender, EventArgs args)
    {
      ThawOneLevel();
    } // end ThawOneLevel
    
    protected abstract bool Take();

    protected abstract void Fill(Entity entity);

    protected virtual void Fill()
    {
      Fill(Current);
    }
    
    public void ReceiveEvent(Whitemice.ZOGI.ServerEvent args)
    {
      Application.Invoke(delegate { this.ProcessEvent(args); } );
    }
    
    public abstract void ProcessEvent(Whitemice.ZOGI.ServerEvent args);
    
    protected virtual void Save(Entity entity)
    {
      Save(entity, false);
    }
    
		protected virtual void Save(Entity entity, bool exitOnSave)
		{
      PutCommand  command;

      this.ZLOG("Save");
		  if (Take())
      {
        this.ZLOG("Take succeeding.");
        Freeze();
        if (entity.ObjectId < 0)
          Unregister(entity, false);
        closeOnThaw = exitOnSave;
        command = new PutCommand(entity, ":save");
        command.Callback = callback;
        Server.Connection.RunCommand(command);
      } else this.ZLOG("Save aborted due to take failure.");
		} // end Save
		
		protected virtual void Remove(Entity entity)
		{
      DeleteCommand command;

      Freeze();
      closeOnThaw = true;
      command = new DeleteCommand(entity, ":remove");
      command.Callback = callback;
      Server.Connection.RunCommand(command);
		} // end Remove

    protected virtual string GetCommandFromContext(object context)
    {
      string command;
      
      try
      {
        if (context is Array)
            command = ((string)(((object[])context).ElementAt(0))).Split(':')[1];
        else if (context is String)
          {
            command = (context as String).Split(':')[1];  
          } else 
            {
              this.ZLOG("Unable to determine a command for EntityWindow callback.");
              command = null;
            }
      } catch(Exception ex)
        {
          command = null;
          this.ZLOG("Exception processing context of EntityWindow callback.");
          this.ZLOG(ex.Message);
          throw ex;
        }
      return command;
    }

    protected virtual bool RunCallbackCommand(string command, RPCEventArgs args)
    {
      switch(command)
      {
        case "remove":
          RemoveCallback(null, args.Exception, args.Context);
        break;
        case "save":
          if (args.IsError)
            SaveCallback(null, args.Exception, args.Context);
            else SaveCallback(args.Payload.ElementAt(0), null, args.Context);
        break;
        case "add-child":
          if (args.IsError)
            AddChildCallback(null, args.Exception, args.Context);
            else AddChildCallback(args.Payload.ElementAt(0), null, args.Context);
        break;
        case "remove-child":
          this.ZLOG(":remove-child");
          RemoveChildCallback(null, args.Exception, args.Context);
        break;
        case "assign":
          if (args.IsError)
            AssignCallback(null, args.Exception, args.Context);
            else AssignCallback(args.Payload.ElementAt(0), null, args.Context);
        break;
        case "unassign":
          if (args.IsError)
            UnassignCallback(null, args.Exception, args.Context);
            else UnassignCallback(args.Payload.ElementAt(0), null, args.Context);
        break;
        case "present":
          if (args.IsError)
            PresentCallback(null, args.Exception, args.Context);
            else PresentCallback(args.Payload.ElementAt(0), null, args.Context);
        break;
        case "fill":
          if (args.IsError)
            FillCallback(null, args.Exception, args.Context);
            else FillCallback(args.Payload.ElementAt(0), null, args.Context);
        break;
        case "multi-fill":
          if (args.IsError)
            MultifillCallback(null, args.Exception, args.Context);
            else MultifillCallback(args.Payload, null, args.Context);
        break;
        default:
          return true;
      }
      return false;
    } // end RunCallbackCommand

    public virtual void ReceiveRPCCall(RPCEventArgs args)
    {
      var command = this.GetCommandFromContext(args.Context);
      this.ZLOG(string.Format("Received callback with command {0}", command));
      RunCallbackCommand(command, args);
    } // end ReceiveRPCCall

    protected virtual void SaveCallback(Entity entity, Exception exception, object context)
    {
      throw new Exception("Entity window does not implement save");
    }
    
    protected virtual void FillCallback(Entity entity, Exception exception, object context)
    {
      this.ZLOG("Using default FallCallback.");
      if (exception == null)
      {
        if (entity.ObjectId == Current.ObjectId)
          Fill(Current);
        Thaw();
      } else
        {
          new MessageBox(exception);
          Unregister(Current, true);
        }
    }

    protected virtual void MultifillCallback(IEnumerable<Entity> result, Exception exception, object context)
    {
      throw new Exception("Entity window does not implement multi-fill");
    } 

    protected virtual void RemoveCallback(Entity entity, Exception exception, object context)
    {
      throw new Exception("Entity window does not implement remove");    
    }

    protected virtual void AddChildCallback(Entity entity, Exception exception, object context)
    {
      throw new Exception("Entity window does not implement add-child");
    }

    protected virtual void RemoveChildCallback(Entity entity, Exception exception, object context)
    {
      throw new Exception("Entity window does not implement remove-child");
    }

    protected virtual void AssignCallback(Entity entity, Exception exception, object context)
    {
      throw new Exception("Entity window does not implement assign");  
    }

    protected virtual void UnassignCallback(Entity entity, Exception exception, object context)
    {
      throw new Exception("Entity form does not implement unassign");   
    }

		protected virtual void PresentCallback(Entity _entity, Exception _exception, object context)
		{
		  if (_exception == null)       
		  {
		    Present(_entity, null, _exception);
		  } else
        {
          // Error
        }
		}    
		
		public bool IsAlive
		{
		  get { return isAlive; }
		} // end IsAlive
		
		/// <summary>
		/// Delist the relation of the window from the specified entity
		/// </summary>
		/// <param name="entity">
		/// A <see cref="Whitemice.ZOGI.Entity"/>
		/// </param>
		/// <param name="close">
		/// A <see cref="System.Boolean"/>
		/// </param>
		protected virtual void Unregister(Entity entity, bool close)
		{
		  if (close)
		  {
		    isAlive = false;
		    Registry.UnregisterForNotification(this);
		    this.Destroy();
		  } else Registry.UnregisterForNotification(entity, this);
		} // end Unregister

    protected virtual void Register(Entity entity)
    {
      Registry.RegisterForNotification(entity, this);
    }
    
		protected virtual void Present(Entity _entity, object _context, Exception _exception)
		{
      this.ZLOG(string.Format("Request to present {0}#{1}", _entity.EntityName, _entity.ObjectId));
			switch (_entity.EntityName)
			{
			  case "Appointment":
			    if (!(GUI.RaiseWindow(_entity)))
			      new AppointmentWindow((_entity as Appointment));
			    break;
				case "Contact":
					if (!(GUI.RaiseWindow(_entity)))
						new ContactWindow((_entity as Contact));
					break;
				case "Enterprise":
					if (!(GUI.RaiseWindow(_entity)))
						new EnterpriseWindow((_entity as Enterprise));
					break;					
				case "Task":
					if (!(GUI.RaiseWindow(_entity)))
						new TaskWindow((_entity as Task));
					break;
				case "Project":
					if (!(GUI.RaiseWindow(_entity)))
						new ProjectWindow((_entity as Project));
					break;											
			} // end entity type switch   
		} // end present entity

    public abstract Entity Current { get; }

    protected void EntityNameCheck(Entity entity, Type entityName)
    {
      if (!(entityName.Equals(entity.GetType())))
        throw new Exception("Inappropriate entity provided to EntityWindow.");
    }
  } // end EntityWindow
} // end namespace
